package org.tea.inventory.db.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.tea.inventory.db.dao.AlumniOrganizeMapper;
import org.tea.inventory.db.dao.AlumniOrganizeUserCustomMapper;
import org.tea.inventory.db.dao.AlumniOrganizeUserMapper;
import org.tea.inventory.db.dao.AlumniUserMessageMapper;
import org.tea.inventory.db.domain.AlumniOrganize;
import org.tea.inventory.db.domain.AlumniOrganizeUser;
import org.tea.inventory.db.domain.AlumniOrganizeUserCustom;
import org.tea.inventory.db.domain.AlumniUser;
import org.tea.inventory.db.util.wx.entity.MessageData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AlumniOrganizeUserService {

    @Autowired
    private AlumniOrganizeUserMapper alumniOrganizeUserMapper;

    @Autowired
    private AlumniOrganizeUserCustomMapper alumniOrganizeUserCustomMapper;

    @Autowired
    private AlumniOrganizeMapper alumniOrganizeMapper;

    @Autowired
    private AlumniUserMessageMapper alumniUserMessageMapper;

    @Autowired
    private UserService userService;


    @Transactional(rollbackFor = Exception.class)
    public int insertSelective(AlumniOrganizeUser record){
        return alumniOrganizeUserMapper.insertSelective(record);
    }

    public AlumniOrganizeUser selectByPrimaryKey(Integer id){
        return alumniOrganizeUserMapper.selectByPrimaryKey(id);
    }

    @Transactional(rollbackFor = Exception.class)
    public int updateByPrimaryKeySelective(AlumniOrganizeUser record){
        return alumniOrganizeUserMapper.updateByPrimaryKeySelective(record);
    }


    public int auditOrganizeUser(AlumniOrganizeUser record){

        int f = alumniOrganizeUserMapper.updateByPrimaryKeySelective(record);

        AlumniOrganizeUser alumniOrganizeUser = alumniOrganizeUserMapper.selectByPrimaryKey(record.getId());

//        AlumniUserMessage message = new AlumniUserMessage();
//        message.setFkUserId(alumniOrganizeUser.getFkUserId()+"");
//        message.setMessageType("notification");
//        message.setCreateTime(new Date());
//        message.setIsRead(false);
//        message.setIsDelete(false);
//        message.setFromUserId(record.getAuthUserId()+"");

        if ("1".equals(record.getIsNormal())){


            AlumniOrganize alumniOrganize = alumniOrganizeMapper.selectByPrimaryKey(record.getFkOrganizeId());
//            message.setContent("您申请的"+ alumniOrganize.getOrganizeName()+"审核通过!");
//            alumniUserMessageMapper.insertSelective(message);

            userService.sendMessage(
                    alumniOrganizeUser.getFkUserId()+"",
                    "notification",
                    "您申请的"+ alumniOrganize.getOrganizeName()+"审核通过!",
                    record.getAuthUserId()+"");

            // 发送微信消息
            AlumniUser u  = userService.findById(alumniOrganizeUser.getFkUserId());
            MessageData msgData = new MessageData();
            msgData.setKeyword1(u.getUserName());
            msgData.setKeyword2(alumniOrganize.getOrganizeName()+"专委会申请");
            msgData.setKeyword3("通过");
            msgData.setKeyword4("您申请的"+ alumniOrganize.getOrganizeName()+"审核通过!");
            userService.sendWXMSG(alumniOrganizeUser.getFkUserId(),msgData);

        } else if ("2".equals(record.getIsNormal())){
            AlumniOrganize alumniOrganize = alumniOrganizeMapper.selectByPrimaryKey(record.getFkOrganizeId());
//            message.setContent(record.getAuthMemo());
//            alumniUserMessageMapper.insertSelective(message);
            if (!"".equals(record.getAuthMemo()) && record.getAuthMemo()!=null) {
                userService.sendMessage(
                        alumniOrganizeUser.getFkUserId()+"",
                        "notification",
                        "您申请的"+ alumniOrganize.getOrganizeName()+"审核不通过!拒绝原因:"+record.getAuthMemo(),
                        record.getAuthUserId()+"");

            } else {
                userService.sendMessage(
                        alumniOrganizeUser.getFkUserId()+"",
                        "notification",
                        "您申请的"+ alumniOrganize.getOrganizeName()+"审核不通过!",
                        record.getAuthUserId()+"");
            }

            AlumniUser u  = userService.findById(alumniOrganizeUser.getFkUserId());
            MessageData msgData = new MessageData();
            msgData.setKeyword1(u.getUserName());
            msgData.setKeyword2(alumniOrganize.getOrganizeName()+"专委会申请");
            msgData.setKeyword3("驳回");
            msgData.setKeyword4("您申请的"+ alumniOrganize.getOrganizeName()+"审核不通过!");
            userService.sendWXMSG(alumniOrganizeUser.getFkUserId(),msgData);
        }

        return f;
    }


    @Transactional(rollbackFor = Exception.class)
    public int updateDeleteByPrimaryKeySelectiveBatch(List<String> list,Integer adminUserId,Integer orgId){

        AlumniOrganizeUser admin = selectOrgUserByOrgIdAndUserId(orgId,adminUserId);

        int r = 0;

        for (String orgUserId:list){

            AlumniOrganizeUser ou = alumniOrganizeUserMapper.selectByPrimaryKey(Integer.parseInt(orgUserId));
            if("2".equals(admin.getPriType()) && "2".equals(ou.getPriType())){
                throw new RuntimeException();
            }

            AlumniOrganizeUser alumniOrganizeUser = new AlumniOrganizeUser();
            alumniOrganizeUser.setId(Integer.parseInt(orgUserId));
            alumniOrganizeUser.setIsDelete(false);
            alumniOrganizeUser.setPriType("3");
            alumniOrganizeUser.setIsNormal("0");
            alumniOrganizeUser.setDeleteDate(LocalDateTime.now());
            alumniOrganizeUser.setModifyDate(LocalDateTime.now());
            alumniOrganizeUser.setModifyUserId(adminUserId);

            r = alumniOrganizeUserMapper.updateByPrimaryKeySelective(alumniOrganizeUser);
        }


        return r;
    }

    @Transactional(rollbackFor = Exception.class)
    public int updatePriTypeByPrimaryKeySelectiveBatch(List<String> list,Integer adminUserId,Integer orgId){
        AlumniOrganizeUser admin = selectOrgUserByOrgIdAndUserId(orgId,adminUserId);
        int r = 0;

        for (String orgUserId:list){


            AlumniOrganizeUser alumniOrganizeUser = new AlumniOrganizeUser();
            alumniOrganizeUser.setId(Integer.parseInt(orgUserId));
            alumniOrganizeUser.setPriType("2");
            alumniOrganizeUser.setModifyDate(LocalDateTime.now());
            alumniOrganizeUser.setModifyUserId(adminUserId);

            r = alumniOrganizeUserMapper.updateByPrimaryKeySelective(alumniOrganizeUser);
        }


        return r;
    }



    /**
     * 根据组织id查询用户
     *
     * @param orgId 组织id
     *
     * @return
     */
    public Map<String,Object> selectByOrgId(Integer orgId,Integer page,Integer limit){

        PageHelper.startPage(page, limit);

        AlumniOrganizeUserCustom user = new AlumniOrganizeUserCustom();
        user.setFkOrganizeId(orgId);

        List<AlumniOrganizeUserCustom> list = alumniOrganizeUserCustomMapper.selectOrganizeUserBySelective(user);

        PageInfo pageinfo = new PageInfo(list);
        Map<String,Object> resMap = new HashMap<String,Object>();
        resMap.put("items",list);
        resMap.put("pageNum",pageinfo.getPageNum());
        resMap.put("pageSize", pageinfo.getPageSize());
        resMap.put("startRow", pageinfo.getStartRow());
        resMap.put("endRow", pageinfo.getEndRow());
        resMap.put("total", pageinfo.getTotal());
        resMap.put("pages", pageinfo.getPages());

        return resMap;
    }



    /**
     * 根据组织id查询正常用户用户
     *
     * @param orgId 组织id
     *
     * @return
     */
    public Map<String,Object> selectByOrgIdNoDel(Integer orgId,Integer page,Integer limit){

        PageHelper.startPage(page, limit);

        AlumniOrganizeUserCustom user = new AlumniOrganizeUserCustom();
        user.setFkOrganizeId(orgId);
        user.setIsNormal("1");
        user.setIsDelete(true);

        List<AlumniOrganizeUserCustom> list = alumniOrganizeUserCustomMapper.selectOrganizeUserBySelective(user);

        PageInfo pageinfo = new PageInfo(list);
        Map<String,Object> resMap = new HashMap<String,Object>();
        resMap.put("items",list);
        resMap.put("pageNum",pageinfo.getPageNum());
        resMap.put("pageSize", pageinfo.getPageSize());
        resMap.put("startRow", pageinfo.getStartRow());
        resMap.put("endRow", pageinfo.getEndRow());
        resMap.put("total", pageinfo.getTotal());
        resMap.put("pages", pageinfo.getPages());

        return resMap;
    }


    /**
     *
     * 申请加入组织
     *
     * @param userId 用户id
     * @param orgId 组织id
     * @param memo 申请说明
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int addOrganize(Integer userId,Integer orgId,String memo,String formId){

        AlumniOrganizeUser alumniOrganizeUser = new AlumniOrganizeUser();

        AlumniOrganizeUserCustom userCustom = new AlumniOrganizeUserCustom();
        userCustom.setFkOrganizeId(orgId);
        userCustom.setFkUserId(userId);
        List<AlumniOrganizeUserCustom> list = alumniOrganizeUserCustomMapper.selectOrganizeUserBySelective(userCustom);

        if (list.size() > 0){

            userCustom = list.get(0);
            alumniOrganizeUser.setId(userCustom.getId());
            alumniOrganizeUser.setUserMemo(memo);
            alumniOrganizeUser.setIsNormal("0");
            alumniOrganizeUser.setPriType("3");
            alumniOrganizeUser.setIsDelete(true);
            alumniOrganizeUser.setModifyUserId(userId);
            alumniOrganizeUser.setModifyDate(LocalDateTime.now());

            int u = alumniOrganizeUserMapper.updateByPrimaryKeySelective(alumniOrganizeUser);

            userService.updateUserFormId(userId,formId);

            return u;
        }

        alumniOrganizeUser.setFkOrganizeId(orgId);
        alumniOrganizeUser.setFkUserId(userId);
        alumniOrganizeUser.setIsNormal("0");
        alumniOrganizeUser.setPriType("3");
        alumniOrganizeUser.setCreateDate(LocalDateTime.now());
        alumniOrganizeUser.setUserMemo(memo);
        alumniOrganizeUser.setIsDelete(true);
        alumniOrganizeUser.setIsForbidden(false);

        int f = alumniOrganizeUserMapper.insertSelective(alumniOrganizeUser);

        userService.updateUserFormId(userId,formId);

        return f;
    }

    /**
     * 退出组织
     *
     * @param orgUserId
     * @param delMemo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int delOrganize(Integer orgUserId,String delMemo){
        AlumniOrganizeUser alumniOrganizeUser = new AlumniOrganizeUser();
        alumniOrganizeUser.setId(orgUserId);
        alumniOrganizeUser.setDeleteDate(LocalDateTime.now());
        alumniOrganizeUser.setDeleteMemo(delMemo);
        alumniOrganizeUser.setIsNormal("0");
        alumniOrganizeUser.setIsDelete(false);
        alumniOrganizeUser.setModifyDate(LocalDateTime.now());

        int f = alumniOrganizeUserMapper.updateByPrimaryKeySelective(alumniOrganizeUser);

        return f;
    }


    /**
     * 根据组织id查询正常用户
     *
     * @param orgId
     * @param userId
     * @param userName
     * @param exclusiveOrgUserId
     * @param page
     * @param limit
     * @return
     */
    public Map<String,Object> selectByOrgIdAndUse(Integer orgId,String userName,Integer userId,List<Integer> exclusiveOrgUserId,Integer page,Integer limit){

        PageHelper.startPage(page, limit);

        AlumniOrganizeUserCustom user = new AlumniOrganizeUserCustom();
        user.setFkOrganizeId(orgId);
        user.setIsNormal("1");
        user.setIsDelete(true);
        user.setUserName(userName);
        user.setFkUserId(userId);
        user.setExclusiveOrgUserId(exclusiveOrgUserId);

        List<AlumniOrganizeUserCustom> list = alumniOrganizeUserCustomMapper.selectOrganizeUserBySelective(user);

        PageInfo pageinfo = new PageInfo(list);
        Map<String,Object> resMap = new HashMap<String,Object>();
        resMap.put("items",list);
        resMap.put("pageNum",pageinfo.getPageNum());
        resMap.put("pageSize", pageinfo.getPageSize());
        resMap.put("startRow", pageinfo.getStartRow());
        resMap.put("endRow", pageinfo.getEndRow());
        resMap.put("total", pageinfo.getTotal());
        resMap.put("pages", pageinfo.getPages());

        return resMap;
    }

    /**
     * 根据组织id查询未审核的用户
     *
     * @param orgId
     * @param page
     * @param limit
     * @return
     */
    public Map<String,Object> selectNoNormalOrgUserByOrgId(Integer orgId,Integer page,Integer limit) {

        AlumniOrganizeUserCustom user = new AlumniOrganizeUserCustom();
        user.setFkOrganizeId(orgId);
        user.setIsNormal("0");

        PageHelper.startPage(page, limit);

        List<AlumniOrganizeUserCustom> list = alumniOrganizeUserCustomMapper.selectOrganizeUserBySelective(user);

        PageInfo pageinfo = new PageInfo(list);
        Map<String,Object> resMap = new HashMap<String,Object>();
        resMap.put("items",list);
        resMap.put("pageNum",pageinfo.getPageNum());
        resMap.put("pageSize", pageinfo.getPageSize());
        resMap.put("startRow", pageinfo.getStartRow());
        resMap.put("endRow", pageinfo.getEndRow());
        resMap.put("total", pageinfo.getTotal());
        resMap.put("pages", pageinfo.getPages());

        return resMap;

    }

    /**
     * 获取未审核成员
     *
     * @param adminUserId
     * @param OrgId
     * @param page
     * @param limit
     * @return
     */
    public Map<String,Object> selectOrganizeNoNormalByUserIdAndOrgId(Integer adminUserId, Integer OrgId,Integer page,Integer limit){

        PageHelper.startPage(page, limit);
        List<AlumniOrganizeUserCustom> list = alumniOrganizeUserCustomMapper.selectOrganizeNoNormalByUserIdAndOrgId(adminUserId,OrgId);

        PageInfo pageinfo = new PageInfo(list);
        Map<String,Object> resMap = new HashMap<String,Object>();
        resMap.put("items",list);
        resMap.put("pageNum",pageinfo.getPageNum());
        resMap.put("pageSize", pageinfo.getPageSize());
        resMap.put("startRow", pageinfo.getStartRow());
        resMap.put("endRow", pageinfo.getEndRow());
        resMap.put("total", pageinfo.getTotal());
        resMap.put("pages", pageinfo.getPages());

        return resMap;
    }


    /**
     * 根据组织id和用户id查询组织成员
     *
     * @param orgId
     * @param userId
     * @return
     */
    public AlumniOrganizeUserCustom selectOrgUserByOrgIdAndUserId(Integer orgId,Integer userId){

        AlumniOrganizeUserCustom user = new AlumniOrganizeUserCustom();

        user.setFkOrganizeId(orgId);
        user.setFkUserId(userId);

        List<AlumniOrganizeUserCustom> list = alumniOrganizeUserCustomMapper.selectOrganizeUserBySelective(user);

        if (list.size()>0){
            return list.get(0);
        } else {
            return null;
        }


    }
}
